import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { PageHeaderWrapper } from '@ant-design/pro-layout';

import { Button, Cascader, Divider, Modal, message } from 'antd';
import { useRef, useState } from 'react';
import AddRoadForm from './component/addRoad';
import UpdataRoadForm from './component/updateRoad';
import type { AddRoadItem, RoadItem, UpdateRoadItem } from './types';
import styles from './style.less';
import { getCity, nestedCityCode } from '@/components/assets/nestedCityCode';
import RemoteSelect from '@/components/RemoteSelect';
import { addRoad, deleteRoad, pageQueryRoad, updateRoad } from './service';
import { SUCCESS_CODE } from '@/utils/request';
import { getTenantList } from '@/pages/Tenant/Tenant/service';
import { useModel } from 'umi';

export default () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser?.permissions;
  const { 'ROAD.ADD': add, 'ROAD.DELETE': Delete, 'ROAD.UPDATE': update } = currUser;
  const [addRoadVisible, setAddRoadVisible] = useState<boolean>(false);
  const [updateRoadVisible, setUpdateRoadVisible] = useState<boolean>(false);
  const [roadData, setRoadData] = useState<RoadItem>({ id: '', tenant_id: '' });
  const actionRef = useRef<ActionType>();

  const columns: ProColumns<RoadItem>[] = [
    {
      title: '所属用户',
      dataIndex: 'tenant_id',
      onFilter: true,
      ellipsis: true,
      render: (_, record) => {
        return record.tenant_name;
      },
      renderFormItem: () => (
        <RemoteSelect
          getPopupContainer={(triggerNode) => triggerNode.parentElement} // 保证选择菜单不会随着页面滚动
          fieldNames={{ key: 'id', value: 'id', label: 'name' }}
          request={() => getTenantList({})}
        />
      ),
    },
    {
      title: '路段名称',
      dataIndex: 'name',
      ellipsis: true,
      order: 20,
    },
    {
      title: '设备数量',
      dataIndex: 'device_count',
      ellipsis: true,
      search: false,
    },
    {
      title: '泊位数量',
      dataIndex: 'space_count',
      ellipsis: true,
      search: false,
    },
    {
      title: '所在省市',
      dataIndex: 'address',
      ellipsis: true,
      order: 10,
      renderFormItem: () => (
        <Cascader
          fieldNames={{ label: 'name', value: 'code', children: 'children' }}
          showSearch
          options={nestedCityCode}
        />
      ),
      render: (_, record) => {
        const addList: string[] = record.address?.split('&') || [];
        return getCity(addList[addList.length - 1]);
      },
    },
    {
      title: '更新时间',
      dataIndex: 'update_time',
      ellipsis: true,

      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      ellipsis: true,

      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      ellipsis: true,
      fixed: 'right',
      key: 'option',
      render: (
        _text,
        record,
        //  _, action
      ) => {
        const onClickRemove = () => {
          const { name, id } = record;
          Modal.confirm({
            title: `确定要删除 ${name} 吗？`,
            content: (
              <>
                <p>删除之后无法撤回，请谨慎操作！</p>
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await deleteRoad({ id });
              actionRef.current?.reload();
            },
            centered: true,
            className: styles.deleteMin,
            style: { height: '15vw' },
          });
        };
        return (
          <>
            {update && (
              <a
                onClick={async () => {
                  setUpdateRoadVisible(true);
                  setRoadData(record);
                }}
              >
                修改
              </a>
            )}
            {Delete && (
              <>
                <Divider type="vertical" />
                <a onClick={onClickRemove}>删除</a>
              </>
            )}
          </>
        );
      },
    },
  ];

  let address: string = '';
  const onChangeAddress = (value: any[]) => {
    address = '';
    let first = true;
    if (value !== undefined) {
      value.forEach((item) => {
        if (first) {
          address = item;
          first = false;
        } else {
          address = address + '&' + item;
        }
      });
    }
  };

  const addRoadEvent = async (values: AddRoadItem) => {
    let address: string = '';
    let first = true;
    values.addressCode?.forEach((item) => {
      if (first) {
        address = item;
        first = false;
      } else {
        address = address + '&' + item;
      }
    });
    values.address = address;
    const res = await addRoad(values);
    if (res.code === SUCCESS_CODE) {
      setAddRoadVisible(false);
      message.success('添加成功');
      actionRef.current?.reload();
    } else {
      message.error(res.message || '添加失败');
    }
  };

  const updateRoadEvent = async (values: UpdateRoadItem) => {
    let address: string = '';
    let first = true;
    values.addressCode?.forEach((item: string) => {
      if (first) {
        address = item;
        first = false;
      } else {
        address = address + '&' + item;
      }
    });
    values.address = address;
    const res = await updateRoad(values);
    if (res.code === SUCCESS_CODE) {
      setUpdateRoadVisible(false);
      message.success(res.message);
      actionRef.current?.reload();
    } else {
      message.error(res.message);
    }
  };

  return (
    <PageHeaderWrapper>
      <ProTable<RoadItem>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        editable={{
          type: 'multiple',
        }}
        scroll={{ x: true }}
        request={async (params) => {
          params.page = params.current;
          params.tenant_id = params.tenant_id?.id;
          onChangeAddress(params.address);
          params.address = address;
          const res = pageQueryRoad(params);
          return res;
        }}
        pagination={{
          defaultPageSize: 10,
          size: 'default',
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        dateFormatter="string"
        headerTitle="路段管理列表"
        toolBarRender={() => [
          <>
            {add && (
              <Button
                key="button"
                icon={<PlusOutlined />}
                type="primary"
                onClick={() => {
                  setAddRoadVisible(true);
                }}
              >
                添加
              </Button>
            )}
          </>,
        ]}
      />
      {addRoadVisible && (
        <AddRoadForm
          onSubmit={addRoadEvent}
          onCancel={() => setAddRoadVisible(false)}
          modalVisible={addRoadVisible}
          visibleHandler={() => setAddRoadVisible(false)}
        />
      )}
      {updateRoadVisible && (
        <UpdataRoadForm
          road={roadData}
          onSubmit={updateRoadEvent}
          onCancel={() => setUpdateRoadVisible(false)}
          modalVisible={updateRoadVisible}
          visibleHandler={() => setUpdateRoadVisible(false)}
        />
      )}
    </PageHeaderWrapper>
  );
};
